import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import ArticleDetailView from '../views/ArticleDetailView.vue';
import LoginView from '../views/LoginView.vue';
import RegisterView from '../views/RegisterView.vue';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/articles/:id',
    name: 'article-detail',
    component: ArticleDetailView,
    props: true
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  // 更多路由将在这里添加
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 添加路由守卫
router.beforeEach((to, from, next) => {
  const publicPages = ['/login', '/register', '/', '/articles/:id'];
  const authRequired = !publicPages.includes(to.path);
  const isLoggedIn = localStorage.getItem('token');

  if (authRequired && !isLoggedIn) {
    return next('/login');
  }

  next();
});

export default router;